package io.renren.modules.sys.service.impl;

import io.renren.common.utils.ShiroUtils;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import io.renren.modules.sys.dao.SysExtractDao;
import io.renren.modules.sys.entity.SysExtractEntity;
import io.renren.modules.sys.service.SysExtractService;
import org.springframework.transaction.annotation.Transactional;


@Service("sysExtractService")
public class SysExtractServiceImpl implements SysExtractService {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysExtractDao sysExtractDao;
	
	@Override
	public SysExtractEntity queryObject(Long extractId){
		return sysExtractDao.queryObject(extractId);
	}
	
	@Override
	public List<SysExtractEntity> queryList(Map<String, Object> map){
		return sysExtractDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return sysExtractDao.queryTotal(map);
	}
	
	@Override
	public void save(SysExtractEntity sysExtract){
		//提现类似下注操作，总金额扣除，待结金额增加
		if(sysUserService.bottom(sysExtract.getUserId(), sysExtract.getAmount() * 100)) {
			sysExtractDao.save(sysExtract);

			updateUserInfo(sysExtract);
		}

	}

	private void updateUserInfo(SysExtractEntity sysExtract) {
		SysUserEntity user = ShiroUtils.getUserEntity();
		SysUserEntity updateUser = new SysUserEntity();
		if (!StringUtils.equals(sysExtract.getRealName(), user.getRealName())) {
			updateUser.setRealName(sysExtract.getRealName());
		}
		if (!StringUtils.equals(sysExtract.getBankCard(), user.getBankCard())) {
			updateUser.setBankCard(sysExtract.getBankCard());
		}
		if (!StringUtils.equals(sysExtract.getOpenBank(), user.getOpenBank())) {
			updateUser.setOpenBank(sysExtract.getOpenBank());
		}
		if (updateUser.getRealName() != null || updateUser.getBankCard() != null || updateUser.getOpenBank() != null) {
			updateUser.setUserId(user.getUserId());
			sysUserService.updateUserBank(updateUser);
		}
	}
	
	@Override
	@Transactional
	public void update(SysExtractEntity sysExtract){

		sysUserService.updateUserStayBalance(sysExtract.getUserId(), -sysExtract.getAmount() * 100);

		sysExtractDao.update(sysExtract);
	}
	
	@Override
	public void delete(Long extractId){
		sysExtractDao.delete(extractId);
	}
	
	@Override
	public void deleteBatch(Long[] extractIds){
		sysExtractDao.deleteBatch(extractIds);
	}
	
}
